<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <PageTools :show-before="true">
          <span slot="before">共{{ total }}条记录</span>
          <template slot="after">
            <el-button size="small" type="warning" @click="$router.push('/import?act=employees')">导入</el-button>
            <el-button size="small" type="danger" @click="exportAll">导出全部</el-button>
            <el-button size="small" type="danger" :disabled="checkPermission('employees-add')" @click="exportCheck">导出部分</el-button>
            <el-button size="small" type="primary" :disabled="checkPermission('employees-add')" @click="showDialog=true">新增员工</el-button>
          </template>
        </PageTools>
        <!-- 放置表格和分页 -->
        <el-card>
          <el-table :data="list" border @selection-change="checkRowData=$event">
            <el-table-column type="selection" width="50" />
            <el-table-column type="index" label="序号" sortable="" />
            <el-table-column prop="username" label="姓名" sortable="" />
            <el-table-column width="160" prop="username" label="头像" sortable="">
              <template slot-scope="{row}">
                <img v-imgerror="require('@/assets/common/head.jpg')" :src="row.staffPhoto" height="100px" @click="showImg(row)">
              </template>
            </el-table-column>
            <el-table-column prop="workNumber" label="工号" sortable="" />
            <el-table-column prop="formOfEmployment" :formatter="formOf" label="聘用形式" sortable="">
              <!-- <template>
                <span />
              </template> -->
            </el-table-column>
            <el-table-column prop="departmentName" label="部门" sortable="" />
            <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
              <template slot-scope="{row}">
                {{ row.timeOfEntry | formatDate }}
              </template>
            </el-table-column>
            <el-table-column prop="enableState" label="账户状态" sortable="" />
            <el-table-column label="操作" sortable="" fixed="right" width="280">
              <template slot-scope="{row}">
                <el-button type="text" size="small" @click="$router.push(`/employees/detail/${ row.id}`)">查看</el-button>
                <el-button type="text" size="small">转正</el-button>
                <el-button type="text" size="small">调岗</el-button>
                <el-button type="text" size="small">离职</el-button>
                <el-button type="text" size="small" @click="showRoleSet(row.id)">角色</el-button>
                <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <el-row type="flex" justify="center" align="middle" style="height: 60px">
            <!-- 分页组件 -->
            <el-pagination
              :current-page.sync="query.page"
              :page-sizes="[5,10,15,20]"
              :page-size="query.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              background
              @size-change="sizeChange"
              @current-change="currentChange"
            />
          </el-row>
        </el-card>
      </el-card>
    </div>
    <!-- 添加修改的弹窗 -->
    <el-dialog title="新增员工" :visible.sync="showDialog" @close="formData = {}">
      <!-- 表单 -->
      <el-form ref="formRef" label-width="120px" :model="formData" :rules="formRules">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="formData.username" style="width:50%" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="formData.mobile" style="width:50%" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="入职时间" prop="timeOfEntry">
          <el-date-picker v-model="formData.timeOfEntry" style="width:50%" placeholder="请选择入职时间" />
        </el-form-item>
        <el-form-item label="聘用形式" prop="formOfEmployment">
          <el-select v-model="formData.formOfEmployment" style="width:50%" placeholder="请选择">
            <el-option v-for="item in employeesEnum.hireType" :key="item.id" :label="item.value" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="工号" prop="workNumber">
          <el-input v-model="formData.workNumber" style="width:50%" placeholder="请输入工号" />
        </el-form-item>
        <el-form-item label="部门" prop="departmentName">
          <!-- 级联选择器 -->
          <el-cascader
            v-model="formData.departmentName"
            placeholder="请选择部门"
            :options="options"
            :props="{label:'name',value:'name'}"
            :show-all-levels="false"
            @focus="handleChange"
          />
        </el-form-item>
        <el-form-item label="转正时间" prop="correctionTime">
          <el-date-picker v-model="formData.correctionTime" style="width:50%" placeholder="请选择转正时间" />
        </el-form-item>
      </el-form>
      <!-- footer插槽 -->
      <template v-slot:footer>
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="showDialog=false">取消</el-button>
            <el-button type="primary" size="small" @click="btnOk">确定</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
    <!-- 头像二维码弹窗 -->
    <el-dialog
      title="头像"
      :visible.sync="avatarImg"
      width="30%"
    >
      <!-- 二维码 -->
      <canvas id="canvas" />
    </el-dialog>
    <!-- 员工关联角色 -->
    <RoleSet ref="role-set" />
  </div>
</template>

<script>
import { getEmployeeList, addEmployee, delEmployee } from '@/api/employees'
import employeesEnum from '@/api/constant/employees'
import { getDepartments } from '@/api/departments'
import { tranListToTreeData } from '@/utils/index'
import RoleSet from './components/role-set.vue'
import QRCode from 'qrcode'

export default {
  name: 'Employees',
  components: {
    RoleSet
  },
  data() {
    return {
      list: [],
      query: {
        page: 1,
        size: 5
      },
      total: 0,
      showDialog: false,
      // 表单数据
      formData: {},
      // 表单校验
      formRules: {
        username: [{ required: true, message: '用户姓名不能为空', trigger: 'blur' }, {
          min: 1, max: 4, message: '用户姓名为1-4位'
        }],
        mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }, {
          pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'
        }],
        formOfEmployment: [{ required: true, message: '聘用形式不能为空', trigger: 'blur' }],
        workNumber: [{ required: true, message: '工号不能为空', trigger: 'blur' }],
        departmentName: [
          { type: 'array', required: true, message: '部门不能为空', trigger: 'change' }
        ],
        timeOfEntry: [{ required: true, message: '入职时间', trigger: 'blur' }]
      },
      employeesEnum,
      options: [],
      // 选中的数据
      checkRowData: [],
      avatarImg: false
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // 初始化
    async initData() {
      const { data } = await getEmployeeList(this.query)
      this.list = data.rows
      this.total = data.total
    },
    sizeChange(val) {
      this.query.size = val
      this.initData()
    },
    currentChange(val) {
      this.query.page = val
      this.initData()
    },
    // 格式化聘用形式
    formOf(row, column, cellValue, index) {
      const res = employeesEnum.hireType.find(item => item.id === cellValue)
      return res ? res.value : '未知'
    },
    // 级联选择器
    async handleChange() {
      const { data } = await getDepartments()
      this.options = tranListToTreeData(data.depts, '')
    },
    // 添加员工
    async btnOk() {
      await this.$refs.formRef.validate()
      // 加工数据(对数据进行拷贝再加工)
      const cloneData = JSON.parse(JSON.stringify(this.formData))
      cloneData.departmentName = cloneData.departmentName[cloneData.departmentName.length - 1]
      await addEmployee(cloneData)
      this.$message.success('添加成功')
      this.showDialog = false
      this.initData()
    },
    // 删除员工
    async del(id) {
      await this.$confirm('确认删除吗？')
      await delEmployee(id)
      this.$message.success('删除成功')
      if (this.query.page !== 1 && this.list.length === 1) {
        this.query.page--
      }
      this.initData()
    },
    // 导出所有的数据
    exportAll() {
      // 语法1：import xx from 'xx'
      // 语法2：import {xx} from 'xx'
      // 语法3：import * as xx from 'xx'
      // 语法4：import('模块路径')  动态加载
      import('@/vendor/Export2Excel').then(async excel => {
        // excel 整个模块的所有信息
        // 将JSON数据导出成excel
        // excel.export_json_to_excel({
        //   header: [], // 表头 必填  是数组
        //   data: [], // 具体数据 必填  是二维数组
        //   filename: 'excel-list', // 非必填  导出的文件名
        //   autoWidth: true, // 非必填
        //   bookType: 'xlsx' // 非必填  导出文件类型1·
        // })

        // 1、获取所有的数据
        const { data } = await getEmployeeList({ page: 1, size: 10000 })
        // console.log(data.rows)
        // 2、处理表格数据
        const result = this.formateJsomData(data.rows)
        console.log(result)
        excel.export_json_to_excel({
          header: result.header, // 表头 必填  是数组
          multiHeader: [['姓名', '主要信息', '', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2'],
          data: result.data, // 具体数据 必填  是二维数组
          filename: 'excel-list', // 非必填  导出的文件名
          bookType: 'xlsx' // 非必填  导出文件类型1·
        })
      })
    },
    // 2、处理表格数据
    formateJsomData(rows) {
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 1、获取表头
      const header = Object.keys(headers)
      console.log(header)
      const data = rows.map(item => {
        // item 每一个对象
        return header.map(key => {
          // key是每个中文键，key对应的英文键是headers[key]
          if (['timeOfEntry', 'correctionTime'].includes(headers[key])) {
            return new Date(item[headers[key]]).toLocaleDateString()
          } else if (headers[key] === 'formOfEmployment') {
            var res = employeesEnum.hireType.find(obj => obj.id === item[headers[key]])
            return res ? res.value : '未知'
          } else {
            return item[headers[key]]
          }
        })
      })
      // console.log(data)
      return { data, header }
    },
    // 导出选中数据
    exportCheck(val) {
      import('@/vendor/Export2Excel').then(async excel => {
        // 1、处理表格数据
        const result = this.formateJsomData(this.checkRowData)
        console.log(result)
        excel.export_json_to_excel({
          header: result.header, // 表头 必填  是数组
          multiHeader: [['姓名', '主要信息', '', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2'],
          data: result.data, // 具体数据 必填  是二维数组
          filename: '员工数据-选中', // 非必填  导出的文件名
          bookType: 'xlsx' // 非必填  导出文件类型1·
        })
      })
    },
    // 预览二维码
    showImg(row) {
      console.log(row.staffPhoto)
      if (!row.staffPhoto) return this.$message.warning('暂无头像')
      this.avatarImg = true
      this.$nextTick(_ => {
        QRCode.toCanvas(document.getElementById('canvas'), row.staffPhoto, (error) => {
          if (error) this.$message.error('生成二维码失败')
        })
      })
    },
    async showRoleSet(id) {
      // 当前员工的所有角色
      await this.$refs['role-set'].getUserRole(id)
      // 所有角色
      this.$refs['role-set'].showRoleList()
    }
  }
}
</script>
